$(document).ready(function () {

    $("#storeSelect").selectpicker();
    $("#employeeSelect").selectpicker();
    $("#accountMoneySelect").selectpicker();
    let inputOrderRebackTable = $('#inputOrderRebackTable').DataTable({
        destroy: true,
        searching: false,
        paging: true,//表格分页
        lengthChange: false
    });
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "onclick": null,
        "showDuration": "400",
        "hideDuration": "1000",
        "timeOut": "7000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    setInputOrderNumber($("#inputOrderNumber"))
    setInputOrderDate($("#inpDate"))
    listEmployees($("#employeeSelect"))
    listStores($("#storeSelect"))
    listMoneyAccount($("#accountMoneySelect"))
    //失去焦点事件
    // $('#inputNumber' + product.id).blur(function (){
    //     //数量和进价相乘,设置到金额一列
    //
    //
    // })
    $('#inputOrderRebackTable').on('blur', 'tr',function() {
        var data = inputOrderRebackTable.row(this).data();
        //获取单击那一行的数据
        //去除span标签
        let id = removeSpanLabel(data[0])
        console.log(id)
        let numId='#num'+id;
        let num=$(numId).val()
        let tempPrice = num*data[4]
        let price = '#tempPrice'+id
        $(price).text(tempPrice)
    } );
    $("#caclulate").on('click',function (){
        let rows = $("#inputOrderRebackTable").dataTable().fnGetNodes()
        let sum=0;
        for(let i=0;i<rows.length;i++){
            // let data = $(rows[i].firstElementChild.firstElementChild)[5]
            let id = rows[i].firstElementChild.firstElementChild.innerHTML
            let label='#tempPrice'+id;
            sum=sum+parseFloat($(label).text())
            // let label='#tempPrice'+removeSpanLabel(rows[i].firstElementChild.firstElementChild)
            // console.log(label)
        }
        $('#payMoney').val(sum)
    //    [0].firstElementChild.firstElementChild
    })

});

/**
 * 使用正则表达式去除span标签
 * @param str
 * @returns {string}
 */
function removeSpanLabel(str){
    var r=/<span[^>]*>([^<]*)<\/span>/ig;
    var m = r.exec(str);
    return m[1]
}

/**
 * 保存进货单据
 */
function rebackOrderProduct(inputOrderId){
    let rebackOrder={}
    rebackOrder.orderId = $('#inputOrderNumber').val()
    rebackOrder.supplier= $('#supplierId').val()
    rebackOrder.employeeId = $('#employeeSelect').val()
    rebackOrder.accountMoeny = $('#accountMoneySelect').val()
    rebackOrder.storeId = $('#storeIdSelect').val()
    rebackOrder.inputDate = $("#inpDate").val()
    rebackOrder.price = $('#payMoney').val()
    rebackOrder.back = $('#backup').val()

    //找到表格内的所有内容，获取id和数量
    let rows = $("#inputOrderRebackTable").dataTable().fnGetNodes()
    let products=[]
    for(let i=0;i<rows.length;i++){
        // let data = $(rows[i].firstElementChild.firstElementChild)[5]
        let id = rows[i].firstElementChild.firstElementChild.innerHTML
        let label='#num'+id;
        let product={}
        product.id=id;
        product.num=$(label).val()
        products.push(product)
    }
    rebackOrder.rebackProduct=products
    //商品信息
    $.ajax({
        type: 'post',
        url: "/admin/business/inputReback/connectSave/"+inputOrderId,
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(rebackOrder),
        success: function (resp) {
            console.log(resp)
            if (resp.data){
                toastr.success(resp.message,'提示')
                setTimeout(function () {
                    window.location.reload()
                },2000)
            }else{
                toastr.error(resp.message,'提示')
            }
        }
    });
}



/**
 * 列出所有的支付账户信息
 */
function listMoneyAccount(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/moneyAccount/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].accId + '" >' + data[i].accName + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 金额计算
 */
function payMoney() {
    let money = localStorage.getItem('payMoney')
    $('#payMoney').val(money)
    localStorage.removeItem('payMoney')
}

/**
 * 列出所有的库存地址
 * @param obj
 */
function listStores(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/store/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].bstoId + '" >' + data[i].bstoTitle + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 列出所有的职工
 * @param obj
 */
function listEmployees(obj) {
    $.ajax({
        type: 'get',
        url: "/admin/info/employee/list",
        dataType: 'json',
        success: function (data) {
            let select = obj;
            for (var i = 0; i < data.length; i++) {
                select.append('<option value="' + data[i].id + '" >' + data[i].name + '</option>');
            }
            select.selectpicker('refresh');
            select.selectpicker('render');
        }
    });
}

/**
 * 默认进货日期
 * @param obj
 */
function setInputOrderDate(obj) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    obj.val(year + '-' + month + '-' + day)
}

/**
 * 设置单据编号
 */
function setInputOrderNumber(obj) {
    //日期格式化为指定格式
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }

        return fmt;
    }
    obj.val(new Date().format("yyyyMMddhhmmss"))
}




